package net.yyge.apksigner.signer.utils;

import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.x500.style.BCStyle;
import org.spongycastle.jce.X509Principal;

import java.util.*;

/**
 * Helper class for dealing with the distinguished name RDNs.
 */
public class DistinguishedNameValues extends LinkedHashMap<ASN1ObjectIdentifier, String> {

    public DistinguishedNameValues() {
        put(BCStyle.C, "");
        put(BCStyle.ST, "");
        put(BCStyle.L, "");
        put(BCStyle.STREET, "");
        put(BCStyle.O, "");
        put(BCStyle.OU, "");
        put(BCStyle.CN, "");
    }

    @Override
    public String put(ASN1ObjectIdentifier key, String value) {
        if (containsKey(key)) {
            super.put(key, value); // preserve original ordering
        } else {
            super.put(key, value);
        }
        return value;
    }

    public void setCountry(String country) {
        put(BCStyle.C, country);
    }

    public void setState(String state) {
        put(BCStyle.ST, state);
    }

    public void setLocality(String locality) {
        put(BCStyle.L, locality);
    }

    public void setStreet(String street) {
        put(BCStyle.STREET, street);
    }

    public void setOrganization(String organization) {
        put(BCStyle.O, organization);
    }

    public void setOrganizationalUnit(String organizationalUnit) {
        put(BCStyle.OU, organizationalUnit);
    }

    public void setCommonName(String commonName) {
        put(BCStyle.CN, commonName);
    }

    public X509Principal getPrincipal() {
        Vector<ASN1ObjectIdentifier> identifiers = new Vector<>();
        Vector<String> values = new Vector<>();
        for (Map.Entry<ASN1ObjectIdentifier, String> entry : this.entrySet()) {
            identifiers.add(entry.getKey());
            values.add(entry.getValue());
        }
        return new X509Principal(identifiers, values);
    }
}